using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Reflection;
using System.Linq;
using System;
using CustomLitJson;
using System.IO;

public class ProjectBuildPiplineWindow : EditorWindow
{
	[MenuItem("com.pzy.*/ProjectBuildPipline/Window")]
	public new static void Show()
	{
		var window = EditorWindow.GetWindow<ProjectBuildPiplineWindow>("Project Build Pipline", true) as ProjectBuildPiplineWindow;
		window.Show(true);
	}

	Dictionary<Type, object> schemaToParamDicDic = new Dictionary<Type, object>();
	object GetOrCreateParam(Type schemaType)
    {
		if(schemaToParamDicDic.ContainsKey(schemaType))
        {
            return schemaToParamDicDic[schemaType];
        }
        var paramType = ProjectBuildPipline.GetParamTypeOfSchema(schemaType);
        if(paramType == null)
        {
            schemaToParamDicDic[schemaType] = null;
            return null;
        }
        var param = Activator.CreateInstance(paramType);
        schemaToParamDicDic[schemaType] = param;
        return param;
    }
    void SetParam(Type schemaType, object param)
    {
        schemaToParamDicDic[schemaType] = param;
    }


    Dictionary<Type, bool> foldoutDic = new Dictionary<Type, bool>();
    bool GetIsFoldout(Type type)
    {
        var b = foldoutDic.TryGetValue(type, out bool isFoldout);
        if (!b)
        {
            return false;
        }
        return isFoldout;
    }
    void SetIsFoldout(Type type, bool isFoldout)
    {
        foldoutDic[type] = isFoldout;
    }

	GlobalParam globalParam = new GlobalParam();


	void DrawGlobalParam()
	{
        EditorGUILayout.LabelField("Global Param:");
		DrawUtil.DrawObject(globalParam);
    }

	async void DrawSchema(Type schemaType)
	{
        var name = schemaType.Name;
        var attribute = schemaType.GetCustomAttribute<BuildSchemaAttribute>();
        string msg = "";
        BuildTarget buildTarget = BuildTarget.NoTarget;
        if (attribute != null)
        {
            msg = attribute.msg;
            buildTarget = attribute.buildTarget;
        }

        var isFoldout = GetIsFoldout(schemaType);
        var postIsFoldout = EditorGUILayout.BeginFoldoutHeaderGroup(isFoldout, name);
        SetIsFoldout(schemaType, postIsFoldout);

        if (postIsFoldout)
        {
            EditorGUI.indentLevel++;
            // 帮助信息
            if (msg != "")
            {
                EditorGUILayout.HelpBox(msg, MessageType.Info);
            }

            var param = GetOrCreateParam(schemaType);

            // 参数
            if (param != null)
            {
                DrawUtil.DrawObject(param);
            }


            var currentBuildTarget = EditorUserBuildSettings.activeBuildTarget;
            var disabled = buildTarget != BuildTarget.NoTarget && buildTarget != currentBuildTarget;
            if (disabled)
            {
                EditorGUI.BeginDisabledGroup(true);
            }

            // 构建按钮
            if (GUILayout.Button(name))
            {
                Build(name, param, globalParam.env);
            }

            DrawTempalteMenu(schemaType);

            if (disabled)
            {
                EditorGUI.EndDisabledGroup();
            }
            EditorGUI.indentLevel--;
        }


        EditorGUILayout.EndFoldoutHeaderGroup();
    }

    async void Build(string name, object param, string env)
    {
        await ProjectBuildPipline.Build(name, param, env);
    }

    static string saveTemplateName;
    void DrawTempalteMenu(Type schemaType)
    {
        DrawSaveMenu(schemaType);
        DrawReadMenu(schemaType);
    }

    int selectedIndex = 0;
    void DrawReadMenu(Type schemaType)
    {
  
        // read
        EditorGUILayout.BeginHorizontal();

        var nameList = GetTemplateNameList(schemaType);

        selectedIndex = EditorGUILayout.Popup(selectedIndex, nameList);

        if (GUILayout.Button("read"))
        {
            var name = nameList[selectedIndex];
            var param = ProjectBuildPipline.ReadParamTempalte(schemaType, name);
            SetParam(schemaType, param);
        }
        EditorGUILayout.EndHorizontal();
    }

    string[] GetTemplateNameList(Type schemaType)
    {
        var rootPath = $"ProjectSettings/com.pzy.projectBuildPipline/{schemaType.Name}";
        if(!Directory.Exists(rootPath))
        {
            return new string[0];
        }
        var pathList = Directory.GetFiles(rootPath);
        var ret = new string[pathList.Length];
        var index = 0;
        foreach(var path in pathList)
        {
            var name = Path.GetFileNameWithoutExtension(path);
            ret[index] = name;
            index++;
        }
        return ret;
    }

    void DrawSaveMenu(Type schemaType)
    {
        // save
        EditorGUILayout.BeginHorizontal();
        saveTemplateName = EditorGUILayout.TextField(saveTemplateName);
        if (GUILayout.Button("save"))
        {
            var param = GetOrCreateParam(schemaType);
            ProjectBuildPipline.WriteParamTemplate(schemaType, param, saveTemplateName);
        }
        EditorGUILayout.EndHorizontal();
    }


    public void OnGUI()
	{
		DrawGlobalParam();

        EditorGUILayout.LabelField("Build Schemas:");
		var schemaTypeList = ProjectBuildPipline.SchemaTypeList;
		foreach (var type in schemaTypeList)
		{
            DrawSchema(type);

        }
	}

	
	public class GlobalParam
	{
		[DefaultValue("dev")]
		public string env = "dev";
	}
}